﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using UserCtrl;
using System.Collections;
using GRWL.BZSC.UI.CustomCtrl;

namespace GRWL.BZSC.UI
{
    public partial class IssueRqrtFrm : BaseFrm
    {
        /// <summary>
        /// 需求发放量计算方式
        /// </summary>
        enum CountMethod
        {
            按毛需求发放 = 1,
            按净需求发放,
            按实际需求发放
        }

        /// <summary>
        /// 发放需求计划类型
        /// </summary>
        private GRWL.BZSC.Common.EnumCommon.RequirementType _RqrtType;
        /// <summary>
        /// 发放需求计划类型
        /// </summary>
        public GRWL.BZSC.Common.EnumCommon.RequirementType RqrtType
        {
            get
            {
                return _RqrtType;
            }
            set
            {
                _RqrtType = value;
                if (_RqrtType == GRWL.BZSC.Common.EnumCommon.RequirementType.SCXQ)
                {
                    Text = "生产计划发放";
                    tabPage1.Text = "生产计划";
                    tabPage2.Text = "生产计划明细";
                }
                else
                {
                    Text = "采购发放";
                    tabPage1.Text = "采购计划";
                    tabPage2.Text = "采购计划明细";
                }
            }
        }

        /// <summary>
        /// 需求明显临时变量
        /// </summary>
        XRqrtDetail[] RqrtDetailAry;

        public IssueRqrtFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();

            this.codeRule = new CodeRuleFrm.CodeRule();

            this.RqrtType = GRWL.BZSC.Common.EnumCommon.RequirementType.SCXQ;

        }

        private void IssueRqrtFrm_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();
            bindNumType();
            this.dgvRqrt.AutoGenerateColumns = false;
            bindDgvRqrt();
        }

        /// <summary>
        /// 绑定需求发放数量计算方式
        /// </summary>
        private void bindNumType()
        {
            this.cbBoxNumType.Items.Clear();
            Common.BindEnumToComboBox(this.cbBoxNumType, typeof(CountMethod));
        }

        /// <summary>
        ///绑定需求计划数据 
        /// </summary>
        private void bindDgvRqrt()
        {
            bool? isRelease = false;
            if (this.radioButton1.Checked)
                isRelease = false;
            else if (this.radioButton2.Checked)
                isRelease = true;
            else if (this.radioButton3.Checked)
                isRelease = null;

            this.dgvRqrt.Rows.Clear();
            //OTConverter.MapToDataGirdView<XRequirement>(this.dgvRqrt, null, new TB_Requirement());
            XRequirement[] xRqrts = this.BaseDataProxy.GetXRequirements(isRelease, BZSC.Common.EnumCommon.VerifyStatus.已批.ToString());
            if (xRqrts != null)
            {
                //DataTable dt = xRqrts.ConvertToDataTable<TB_Requirement>();
                //this.dgvRqrt.DataSource = xRqrts;
                foreach (XRequirement xr in xRqrts)
                {
                    this.dgvRqrt.Rows.Add(new object[] { xr.Requirement.id, false, xr.Requirement.isRelease, xr.Requirement.code, Convert.ToDateTime(xr.Requirement.rqrtDate).ToShortDateString(), xr.OperatorName, xr.DepartmentName, xr.Requirement.status, xr.AssessorName, xr.Requirement.memo });
                }
            }
        }

        private void bindDgvDetail()
        {
            this.dgvDetail.Rows.Clear();
            ArrayList ary = new ArrayList();
            if (this.dgvRqrt.Rows != null)
            {
                for (int i = 0; i < this.dgvRqrt.Rows.Count; i++)
                {
                    if (this.dgvRqrt.Rows[i].Cells[1].Value != null)
                    {
                        if (Convert.ToBoolean(this.dgvRqrt.Rows[i].Cells[1].Value))
                        { ary.Add(this.dgvRqrt.Rows[i].Cells[0].Value); }
                    }
                }
                if (ary.Count > 0)
                {
                    RqrtDetailAry = this.BaseDataProxy.GetXRqrtDetails((int[])ary.ToArray(typeof(int)));
                    if (RqrtDetailAry != null)
                    {
                        foreach (XRqrtDetail xrd in RqrtDetailAry)
                        {
                            int rowId = this.dgvDetail.Rows.Add(new object[] {
                                xrd.RqrtDetail.id,
                                false,
                                xrd.RqrtDetail.isRelease,
                                xrd.RqrtDetail.structlevel,
                                xrd.RqrtDetail.orderId,
                                xrd.RqrtDetail.orderCode,
                                xrd.RqrtDetail.orderDetailId,                                
                                xrd.RqrtDetail.rqrtCode,
                                xrd.RqrtDetail.rqrt,
                                xrd.RqrtDetail.material,
                                xrd.RqrtDetail.materialCode,
                                xrd.MaterialName,
                                xrd.RqrtDetail.rqrtDate,
                                xrd.RqrtDetail.source,
                                xrd.RqrtDetail.department,
                                xrd.DepartmentName,
                                xrd.RqrtDetail.netNeeds,
                                xrd.RqrtDetail.releaseDate.ToString(),
                                xrd.RqrtDetail.hairNeeds,
                                xrd.RqrtDetail.specs,
                                xrd.CategoryName,
                                xrd.Unit,
                                xrd.RqrtDetail.prdnCode,
                                xrd.RqrtDetail.prdtPrjtId,
                                xrd.RqrtDetail.prdtPrjtCode,
                                xrd.RqrtDetail.isMain,
                                xrd.RqrtDetail.isNominal,
                                xrd.RqrtDetail.memo});
                            this.dgvDetail.Rows[rowId].Cells[1].ReadOnly = xrd.RqrtDetail.isRelease;
                        }
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 发放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIssue_Click(object sender, EventArgs e)
        {
            if (this.dgvRqrt.Rows!=null && this.dgvDetail.Rows != null)
            {                
                    ArrayList checkedList  = new ArrayList();
                    for (int i = 0; i < this.dgvDetail.Rows.Count; i++)
                    {
                        DataGridViewRow row = this.dgvDetail.Rows[i];
                        bool check = Convert.ToBoolean(row.Cells[1].Value);
                        if (check)
                            checkedList.Add(row.Cells[0].Value.ToString());
                    }

                    if (checkedList.Count == 0)
                    {
                        MessageBox.Show("请选择要发放的需求明细！");
                        return;
                    }
                    else
                    {
                        int method = 1;
                        if (this.cbBoxNumType.Text != CountMethod.按毛需求发放.ToString())
                            method = 2;
                        string[] ary = (string[])checkedList.ToArray(typeof(string));
                        int rqrtId = this.RqrtDetailAry.First().RqrtDetail.rqrt;
                        if (this.BaseDataProxy.IssueRequirement(method, SysLoginUserInfo.UserId, SysLoginUserInfo.DepartmentId, this.dtpIssueDate.Value, rqrtId, string.Join(",", ary)))
                        {
                            MessageBox.Show("需求发放成功！");
                            this.dgvDetail.Rows.Clear();
                            this.dgvRqrt.Rows.Clear();
                        }
                    }
            }
        }

        /// <summary>
        /// 生成生产单
        /// </summary>
        /// <param name="dept"></param>
        /// <param name="materialId"></param>
        /// <param name="materialCode"></param>
        /// <param name="memo"></param>
        /// <param name="orderCode"></param>
        /// <param name="orderDetailId"></param>
        /// <param name="orderId"></param>
        /// <param name="orderNum"></param>
        /// <param name="rqrtId"></param>
        /// <param name="rqrtCode"></param>
        /// <param name="rqrtDetailId"></param>
        /// <param name="specs"></param>
        /// <param name="structLevel"></param>
        private TB_PrdnDetail getPrdnDetail(TB_Production p, object dept, object materialId, object materialCode, object memo, object orderCode, object orderDetailId,
            object orderId, object orderNum, object rqrtId, object rqrtCode, object rqrtDetailId, object specs, object prjtId, object structLevel, object isNominal)
        {
            try
            {
                if (!Convert.ToBoolean(isNominal))//虚设件、采购件不做生产
                {
                    //生产单明细                            
                    TB_PrdnDetail pd = new TB_PrdnDetail();
                    if (dept != null)
                        pd.department = Convert.ToInt32(dept);
                    pd.material = Convert.ToInt32(materialId);
                    pd.materialCode = materialCode.ToString();
                    pd.memo = memo.ToString();
                    pd.orderCode = orderCode.ToString();
                    if (orderDetailId != null)
                        pd.orderDetailId = Convert.ToInt32(orderDetailId);
                    if (orderId != null)
                        pd.orderId = Convert.ToInt32(orderId);

                    if (orderNum != null)
                        pd.orderNum = Convert.ToDecimal(orderNum);

                    pd.planOutput = pd.orderNum;
                    pd.prdnCode = p.code;
                    pd.releaseDate = DateTime.Now;
                    pd.rqrtCode = rqrtCode.ToString();
                    pd.rqrtDetailId = Convert.ToInt32(rqrtDetailId);
                    pd.rqrtId = Convert.ToInt32(rqrtId);
                    pd.specs = specs.ToString();
                    if (structLevel != null)
                        pd.structLevel = Convert.ToInt16(structLevel);

                    if (prjtId != null)//产品有下级工程
                    {
                        TB_ProductProject pp = this.BaseDataProxy.GetPrdtPrjt(Convert.ToInt32(prjtId));
                        if (pp != null)
                        {
                            XPrjtWorkstage[] pws = this.BaseDataProxy.FindPrjtWorkstages(pp.id);
                            if (pws != null)
                            {
                                List<TB_PrdnWorkstage> wsAry = new List<TB_PrdnWorkstage>();
                                foreach (XPrjtWorkstage pw in pws)
                                {
                                    TB_PrdnWorkstage prdnWs = new TB_PrdnWorkstage();
                                    prdnWs.fixWastage = pw.PrjtWorkstage.fixWastage;
                                    prdnWs.inNum = pw.PrjtWorkstage.inNum;
                                    prdnWs.outNum = pw.PrjtWorkstage.outNum;
                                    prdnWs.sort = pw.PrjtWorkstage.sort;
                                    prdnWs.wastageRate = pw.PrjtWorkstage.wastageRate;
                                    prdnWs.workstage = Convert.ToInt32(pw.PrjtWorkstage.workstage);

                                    XPrjtElement[] pes = this.BaseDataProxy.FindPrjtElements(pw.PrjtWorkstage.id);
                                    if (pes != null)
                                    {
                                        List<TB_PrdnMaterial> pesAry = new List<TB_PrdnMaterial>();
                                        foreach (XPrjtElement pe in pes)
                                        {
                                            TB_PrdnMaterial prdnMl = new TB_PrdnMaterial();
                                            prdnMl.dosage = pe.PrjtElement.dosage;
                                            prdnMl.fixWastage = pe.PrjtElement.fixWastage;
                                            prdnMl.material = Convert.ToInt32(pe.PrjtElement.material);
                                            prdnMl.sort = pe.PrjtElement.sort;
                                            prdnMl.wastageRate = pe.PrjtElement.wastageRate;
                                            pesAry.Add(prdnMl);
                                        }
                                        prdnWs.TB_PrdnMaterial = pesAry.ToArray();
                                    }
                                    wsAry.Add(prdnWs);
                                }
                                pd.TB_PrdnWorkstage = wsAry.ToArray();
                            }
                        }
                    }

                    return pd;
                }
            }
            catch { }
            return null;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void dgvRqrt_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            this.dgvRqrt.Rows[e.RowIndex].HeaderCell.Value = Convert.ToString(e.RowIndex + 1);//显示行号，也可以设置成显示其他信息 
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            bindDgvRqrt();
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            bindDgvRqrt();
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            bindDgvRqrt();
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 1)
                bindDgvDetail();
            else
                bindDgvRqrt();
        }

        /// <summary>
        /// checkbox列选中后未提交的，在这里处理提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDetail_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.dgvDetail.IsCurrentCellDirty) //有未提交的更//改
            {
                this.dgvDetail.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        /// <summary>
        /// checkbox列选中后未提交的，在这里处理提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvRqrt_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.dgvRqrt.IsCurrentCellDirty) //有未提交的更//改
            {
                this.dgvRqrt.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void dgvRqrt_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dgvRqrt);
        }

        private void dgvRqrt_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dgvRqrt);
        }

        private void dgvDetail_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dgvDetail);
        }

        private void dgvDetail_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dgvDetail);
        }

    }
}
